package net.zjitc.listthree.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.imageio.IIOException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author Administrator
 * @Date 2020/6/18 16:41
 * JDBC工具类
 * 利用Druid数据库连接池
 **/
public class JDBCUtils {
    private static DataSource ds;
    static {
        /*静态代码块，程序加载时执行一次，只执行一次
        * 1.加载配置文件进内存
        * 2.初始化DataSource*/
        try {
            Properties pro=new Properties();
            /*通过类加载器ClassLoader ，将src目录下的配置文件加载进内存*/
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            /*通过Druid 初始化Datasource*/
            ds= DruidDataSourceFactory.createDataSource(pro);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 获取ds
     * @return
     */
    public static DataSource getDataSource(){
        return ds;
    }

    /**
     * 获取连接，通过DataSource获取
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }
}
